﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Bullet : MonoBehaviour
{
    [SerializeField] private float bulletSpeed;
    [SerializeField] private float lifeTime;
    [SerializeField] private float bulletDamage = 20;
    private float lifeTimer;

    private Rigidbody bulletRigid;

    public GameObject targetObj;
    // Start is called before the first frame update
    void Start()
    {
        bulletRigid = this.gameObject.GetComponent<Rigidbody>();
        this.gameObject.transform.LookAt(targetObj.transform);
    }

    // Update is called once per frame
    void Update()
    {
        BulletMovesForward();
        lifeTimer++;
        BulletSelfDestructs();
    }

    void BulletMovesForward()
    {
        bulletRigid.velocity = transform.forward*bulletSpeed;
    }

    void BulletSelfDestructs()
    {
        if (lifeTimer > lifeTime)
        {
            Destroy(this.gameObject);
        }
    }

    private void OnCollisionEnter(Collision other)
    {
        if (other.gameObject != null)
        {
            if (other.gameObject.tag == "Enemy"||other.gameObject.tag == "Enemyfast")
            {
                other.gameObject.GetComponent<EnemyBehavior>().enemyHealth -= bulletDamage;
                Destroy(this.gameObject);
            }

            if (other.gameObject.tag == "Bullet")
            {
                return;
            }
            Destroy(this.gameObject);
        }
        
    }
}
